<template>
  <div class="login">
    <div class="login-container">
      <el-form
        :model="loginForm"
        status-icon
        label-width="150px"
        :rules="loginRules"
      >
        <h1 class="title">vite-vue3</h1>
        <el-form-item :label="$t('message.userName')" prop="username">
          <el-input v-model="loginForm.username" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item :label="$t('message.password')" prop="password">
          <el-input
            type="password"
            v-model="loginForm.password"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSubmit">
            {{ $t('message.login') }}
          </el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import { reactive, toRefs } from 'vue'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'

export default {
  components: {},
  setup() {
    const store = useStore()
    const router = useRouter()
    const data = reactive({
      loginForm: {
        username: 'admin',
        password: '123456'
      }
    })
    const validateName = (rule, value, callback) => {
      const reg = /^[a-zA-Z]+$/g
      if (value === '') {
        callback(new Error('请输入用户名'))
      } else if (!reg.test(value)) {
        callback(new Error('用户名必须为英文字母'))
      } else {
        callback()
      }
    }
    const loginRules = {
      username: [{ validator: validateName, trigger: 'blur' }],
      password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
    }

    const handleSubmit = () => {
      console.log('正在登陆中')
      console.dir(store.dispatch)
      store.dispatch('user/login', data.loginForm).then(() => {
        console.log('登录成功跳转')
        router.push('/welcome')
      })
    }
    return { ...toRefs(data), loginRules, handleSubmit }
  }
}
</script>

<style lang="less" scoped>
.login {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  height: 100vh;
  background-size: 100% 100%;
  /deep/.el-form-item__error {
    color: red;
  }
  .login-container {
    position: relative;
    width: 500px;
    height: 350px;
    margin: 15% auto;
    background: #fff;
    text-align: center;
    border-radius: 5px;
    .title {
      position: relative;
      top: 30px;
      font-family: '华文行楷';
      margin-bottom: 60px;
    }
  }
}
</style>
